package liuch.socketdemov2;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * socket 客户端
 */
@SuppressWarnings("all")
public class SocketClient {

    private Socket socket;

    public SocketClient() {
        try {
            socket = new Socket("127.0.0.1", 8088);

            ServerHandler serverHandler = new ServerHandler(socket);
            new Thread(serverHandler).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            // 通讯
            OutputStream outputStream = socket.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
            PrintWriter pw = new PrintWriter(outputStreamWriter, true);
            Scanner scanner = new Scanner(System.in);
            while (true) {
                pw.println(scanner.nextLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        SocketClient socketClient = new SocketClient();

        socketClient.start();
    }
}
